#!/usr/bin/python
# -*- coding: UTF-8 -*-


import sys
import os
import time
import re
import argparse

sys.path.append("utils")

import config
import fileUtil
import gitUtils
import zipfile
import verUtils
import util
import ftpUtils
import debugUtils
import logUtil
import fir
import pngUtils
import taskUtils

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

# 替换文件中特定的字符串
# files = ["", ""]
# repldata = [{"pattern": "", "repl": ""}, {"pattern": "", "repl": ""}, ]
def replaceStr(files, repldata):
	print("replaceStr() files = %s" % str(files))
	print("replaceStr() repldata = %s" % str(repldata))

	for file in files:
		with open(file,'r') as r:
			lines = r.readlines()

		# tofile = "%s.%s" % (file, "temp") # test
		tofile = file
		with open(tofile,'w') as w:
			for l in lines:
				result = l
				for data in repldata:
					result, number = re.subn(data["pattern"], data["repl"], result)
					if number > 0:
						print("------replaceStr() %s : %s------" % (data["pattern"], data["repl"]))
						print("%s===>\n%s" % (l, result))

				w.write(result)

# 发送邮件 
def sendEmail(toUser, subject, msg):
	ret = True

	try:
		msg = MIMEText(msg,'html','utf-8')
		msg['From'] = formataddr(["dabaoji", config.EMAIL_SENDER]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
		msg['To'] = formataddr([toUser, toUser]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号
		msg['Subject'] = subject # 邮件的主题，也可以说是标题

		server = smtplib.SMTP_SSL(config.SMTP_HOST, config.SMTP_PORT) # 发件人邮箱中的SMTP服务器，端口
		server.login(config.EMAIL_SENDER, config.EMAIL_PASS) # 括号中对应的是发件人邮箱账号、邮箱密码
		server.sendmail(config.EMAIL_SENDER, [toUser,], msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
		server.quit() # 关闭连接

		print("send email to %s success" % toUser)
	except Exception, e: # 如果 try 中的语句没有执行，则会执行下面的 ret=False
		print(str(e))
		print("send email to %s fail" % toUser)
		ret = False

	return ret

# 发送带图片的邮件
# images {"img1": "test-img.png", "img2": "test-img.png"} key 必须对应 msg 中的图片 id
def sendImagesEmail(toUser, subject, msg, images):
	ret = True

	msgRoot = MIMEMultipart('related')

	msgRoot['From'] = formataddr(["dabaoji", config.EMAIL_SENDER]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
	msgRoot['To'] = formataddr([toUser, toUser]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号
	msgRoot['Subject'] = subject # 邮件的主题，也可以说是标题

	msgAlternative = MIMEMultipart('alternative')
	msgRoot.attach(msgAlternative)

	msgAlternative.attach(MIMEText(msg, 'html', 'utf-8'))

	for key, file in images.items():
		# 指定图片为当前目录
		fp = open(file, 'rb')
		msgImage = MIMEImage(fp.read())
		fp.close()

		# 定义图片 ID，在 HTML 文本中引用
		msgImage.add_header('Content-ID', '<%s>' % key)
		msgRoot.attach(msgImage)

	try:
		server = smtplib.SMTP_SSL(config.SMTP_HOST, config.SMTP_PORT) # 发件人邮箱中的SMTP服务器，端口
		server.login(config.EMAIL_SENDER, config.EMAIL_PASS) # 括号中对应的是发件人邮箱账号、邮箱密码
		server.sendmail(config.EMAIL_SENDER, [toUser,], msgRoot.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
		server.quit() # 关闭连接

		print("send email to %s success" % toUser)
	except Exception, e: # 如果 try 中的语句没有执行，则会执行下面的 ret=False
		print(str(e))
		print("send email to %s fail" % toUser)
		ret = False

	return ret

# url 转换成二维码图片
# return img
def urlToQRCode(url, file):
	print("urlToQRCode() url = %s" % url)

	import qrcode

	qr = qrcode.QRCode(
		version=1, 
		error_correction=qrcode.constants.ERROR_CORRECT_L, 
		box_size=5,
		border=4, ) 
	qr.add_data(url) 
	qr.make(fit=True) 
	img = qr.make_image()

	if file:
		img.save(file)

	return img

# Android 包
def buildApk(mode):
	global tcsglobal

	util.startTime()

	# 移除之前打包生成的文件
	outputAPKFileName = os.path.join(tcsglobal["gameHallDir"], config.APK_FILE_NAME)
	fileUtil.remove(outputAPKFileName)

	apkfile = ""

	if mode == "debug":
		stringCMD = "cocos compile -j 8 -p android -m release --ndk-mode debug --compile-script 1 -k \"%s\" -b \"%s\" " % ( config.LUA_ENCRYPT_KEY, config.LUA_ENCRYPT_SIGN )
		util.shellCall( stringCMD )
	elif mode == "release":
		stringCMD = "cocos compile -j 8 -p android -m release --compile-script 1 -k \"%s\" -b \"%s\" " % ( config.LUA_ENCRYPT_KEY, config.LUA_ENCRYPT_SIGN )
		util.shellCall( stringCMD )

	sofile = os.path.join(tcsglobal["gameHallDir"], config.SO_FILE_NAME)
	
	if fileUtil.isFile(sofile):
		logUtil.debug("build %s success" %(sofile))

		if fileUtil.isFile( outputAPKFileName ):
			logUtil.debug("build %s success" % (outputAPKFileName))
			apkfile = outputAPKFileName
		else:
			logUtil.error("build %s fail" %(outputAPKFileName))
	else:
		logUtil.error("build %s fail" %(sofile))
	
	util.endTime()

	return apkfile

# 打 Android 包
def buildAndroid(mode):
	global tcsglobal

	currPath = util.getCurrentPath()

	util.jumpToPath(tcsglobal["gameHallDir"])

	apkfile = buildApk(mode)

	util.jumpToPath(currPath)

	return apkfile

# 打 iOS 包
def buildIOS():
	global tcsglobal

	util.startTime()

	outputIPAFileName = os.path.join(tcsglobal["gameHallDir"], config.IPA_FILE_NAME)
	# 移除之前打包生成的文件
	fileUtil.remove(outputIPAFileName)

	currPath = util.getCurrentPath()

	toolsdir = os.path.join(tcsglobal["gameHallDir"], "tools")
	util.jumpToPath(toolsdir)

	cmd = "./auto_package.sh ios"
	util.shellCall(cmd)

	util.jumpToPath(currPath)

	ipafile = ""
	if fileUtil.isFile( outputIPAFileName ):
		logUtil.debug("build %s success" % ( outputIPAFileName ) )
		ipafile = outputIPAFileName
	else:
		logUtil.error("build %s fail" %( outputIPAFileName ) )

	util.endTime()

	return ipafile

def build(args, platform, outfiles):
	global tcsglobal

	print("-------- build %s ----------" % platform)
	projRoot = os.path.join(config.PROJECT_ROOT)
	print(projRoot)

	# 打包
	distfilename = "tcs-%s-%s-%s" % (args.env, tcsglobal["timestr"], args.mode)
	
	outfile = ""

	if platform == "Android":
		distfilename = distfilename + ".apk"

		outfile = buildAndroid(args.mode)
	elif platform == "iOS":
		distfilename = distfilename + ".ipa"

		outfile = buildIOS()
	else:
		print("args platform = %s is error!" % platform)

	print("distfilename = %s" % (distfilename))

	if outfile != "":
		# 更新任务状态 - 打包成功
		taskUtils.updateTaskStatus(tcsglobal["taskid"], taskUtils.TASK_STATUS_SUCCESSED)

		ftpPath = os.path.join(config.FTP_DIR, tcsglobal["daystr"])

		distdir = os.path.join(config.EXPORT_ROOT, ftpPath)
		if not os.path.exists(distdir):
			os.makedirs(distdir)

		distfile = os.path.join(distdir, distfilename)

		fileUtil.copyFile(outfile, distfile)

		print("final outfile =%s" % (distfile))

		# 上传到 ftp
		ftpUtils.uploadOneFile(distdir, distfilename, ftpPath)

		outfiles.append(distfile)
		
		print("---------- build success ----------")
		print("build args = %s ==> %s" % (str(args), distfile))

		ftpurl = os.path.join("ftp://", config.FTP_HOST, ftpPath, distfilename)
		# result = "build %s success ==> %s" % (platform, ftpurl)
		result = {"success": True, "platform": platform, "ftpurl": ftpurl, "file": distfile, "filename": distfilename}

		# 上传安装包到 fir
		if args.firapitoken and args.firapitoken != "":
			try:
				uploadFileToFir(result, args.firapitoken, args.subhead)
			except:
				# 更新任务状态 - 打包成功，但上传FIR不成功
				taskUtils.updateTaskStatus(tcsglobal["taskid"], taskUtils.TASK_STATUS_SUCCESSED_EXCEPT_FIR)
		
		print("fir result = %s" % str(result))

		return result
	else:
		print("---------- build fail ----------")
		print("build args = %s" % str(args))

		# result = "build %s fail" % (platform)
		result = {"success": False, "platform": platform}
		taskUtils.updateTaskStatus(tcsglobal["taskid"], taskUtils.TASK_STATUS_FAILED)
		return result

# 替换文件中的特定字符串
def changeFiles(args):
	global tcsglobal

	# 替换文件中的特定字符串
	constantsfile = os.path.join(tcsglobal["gameHallDir"], "simulator/win32/src/app/manager/Constants.lua")
	# constantsfile = "E:/autobuildtools/Constants.lua" # test

	if args.env == "test":
		testStr = "TEST_MODE = true"
		envStr = "ENV_VALUE = 2"
	elif  args.env == "pre":
		testStr = "TEST_MODE = false"
		envStr = "ENV_VALUE = 1"
	elif  args.env == "r":
		testStr = "TEST_MODE = false"
		envStr = "ENV_VALUE = 0"
	
	repldata = [
		{"pattern": "TEST_MODE\s*=\s*(true|false)", "repl": testStr},
		{"pattern": "ENV_VALUE\s*=\s*(0|1|2)", "repl": envStr},
	]
	replaceStr([constantsfile], repldata)

# 上传安装包到 fir
def uploadFileToFir(result, token, subhead):
	print("uploadFileToFir() token = %s" % token)

	global tcsglobal

	buildStr = tcsglobal["timestr"]

	if result["success"] and result["file"]:
		appInfo = {"file":result["file"], "type":result["platform"].lower(), "bundle_id":config.FIR_APP_BUNDLE_ID,
			"api_token":token,
			"name":config.FIR_APP_NAME, "version":config.FIR_APP_VERSION,
			"build":buildStr,
			"changelog": "upload by dabaoji: %s\n%s" % (result["filename"], str(subhead))
		}

		installUrl = fir.uploadAppFile(appInfo, 3, 5*60)
		if installUrl:
			result["installurl"] = installUrl

		# 更新打包任务下载链接
		if result["platform"] == "Android":
			taskUtils.updateTask(tcsglobal["taskid"], {"apkurl": installUrl})
		elif result["platform"] == "iOS":
			taskUtils.updateTask(tcsglobal["taskid"], {"iosurl": installUrl})


# 生成二维码图片
# retrun success
def toQRCodeImage(title, subhead, resultList, file):
	from PIL import Image,ImageDraw,ImageFont

	fontHeight = 30
	space = 0 # 间隙

	textHeight = fontHeight*3
	x = 0
	y = textHeight
	width = 0
	height = 0
	qrCodes = []

	for v in resultList:
		if v["success"] and v.has_key("installurl"):
			qrCode = urlToQRCode(v["installurl"], None)

			x = width

			w, h = qrCode.size
			width = width + w + space
			if h > height:
				height = h

			item = {"name": v["platform"], "qrCode": qrCode, "x": x, "y": y}
			qrCodes.append(item)

	# 标题文字
	titleFont = ImageFont.truetype("msyh.ttf", 20)
	titleTextW = titleFont.getsize(unicode(title,'utf-8'))[0]
	print("titleTextW = %s" % titleTextW)
	if width < titleTextW:
		width = titleTextW

	# 副标题文字
	if subhead and subhead != "":
		subheadFont = ImageFont.truetype("msyh.ttf", 20)
		subheadTextW = subheadFont.getsize(unicode(subhead,'utf-8'))[0]
		print("subheadTextW = %s" % subheadTextW)
		if width < subheadTextW:
			width = subheadTextW

	toImage = Image.new('RGBA', (width, height + textHeight), (255,255,255))

	# 新建绘图对象 
	draw = ImageDraw.Draw(toImage)
	# 选择文字字体和大小 
	font = ImageFont.truetype("msyh.ttf", 20)

	if len(qrCodes) <= 0:
		return False

	for item in qrCodes:
		toImage.paste(item["qrCode"], (item["x"], item["y"]))

		textW = font.getsize(item["name"])[0]
		textX = item["x"] + item["qrCode"].size[0]/2 - textW/2
		# 绘制平台文字 Android 或 iOS
		draw.text((textX, fontHeight*2), item["name"], font=font, fill="#ff0000")

	# 绘制标题文字
	textX = width/2 - titleTextW/2
	if textX < 0:
		textX = 0
	draw.text((textX, 0), unicode(title,'utf-8'), font=titleFont, fill="#000000")

	# 绘制副标题文字
	if subhead and subhead != "":
		textX = width/2 - subheadTextW/2
		if textX < 0:
			textX = 0

		print("subhead = %s" % subhead)
		draw.text((textX, fontHeight), unicode(subhead,'utf-8'), font=subheadFont, fill="#000000")

	toImage.save(file)

	return True

# 发送成功邮件
def sendSuccessEmail(args, shell, resultList):
	global tcsglobal

	# 发送结果邮件
	email = args.email

	subject = "自动打包结果通知 %s %s" % (tcsglobal["timestr"], args.subhead)
	msg = """<p>---------- build %s finish ----------</p>""" % (args.subhead)
	msg = msg + """<p>build shell = %s </p>""" % shell
	msg = msg + """<p>build result:</p>"""

	appFileName = "tcs-%s-%s-%s" % (args.env, tcsglobal["timestr"], args.mode)

	ftpMsg = '''<p>%s ftp:</p>''' % appFileName
	firMsg = '''<p>%s fir:</p>''' % appFileName
	
	for v in resultList:
		ftpStr = ""
		firStr = ""
		qrcodeStr = ""

		if v["success"]:
			ftpStr = '''<p>%s: <a href="%s">%s</a></p>''' % (v["platform"], v["ftpurl"], v["ftpurl"])

			if v.has_key("installurl"):
				firStr = '''<p>%s: <a href="%s">%s</a></p>''' % (v["platform"], v["installurl"], v["installurl"])
			else:
				firStr = '''<p>%s: upload fir fail!''' % (v["platform"])
		else:
			ftpStr = '''<p>%s: build fail!</p>''' % (v["platform"])
			firStr = '''<p>%s: build fail!</p>''' % (v["platform"])

		ftpMsg = ftpMsg + ftpStr
		firMsg = firMsg + firStr

	# 生成二维码
	qrcodeMsg = ""
	qrCodeimages = {}
	qrCodeImgFile = "qrcode.png"
	success = toQRCodeImage(appFileName, args.subhead, resultList, qrCodeImgFile)
	if success:
		imgKey = "qrcode"
		qrCodeimages = {imgKey: qrCodeImgFile}

		qrcodeMsg = qrcodeMsg + '''<p>%s fir:</p>''' % appFileName
		qrcodeMsg = qrcodeMsg + '''<p><img src="cid:%s"></p>''' % imgKey

	msg = msg + '''<p></p>'''
	msg = msg + ftpMsg
	
	if args.firapitoken and args.firapitoken != "":
		msg = msg + '''<p></p>'''
		msg = msg + '''<p>--------------------</p>'''
		msg = msg + '''<p></p>'''
		msg = msg + str(firMsg)

		msg = msg + '''<p></p>'''
		msg = msg + '''<p>--------------------</p>'''
		msg = msg + '''<p></p>'''
		msg = msg + qrcodeMsg

	print("email msg = %s" % msg)
	# sendEmail(email, subject, msg)
	sendImagesEmail(email, subject, msg, qrCodeimages)

# 解析命令行参数
def parserArg():
	print("parserArg()")
	parser = argparse.ArgumentParser()
	parser.add_argument("platform", choices=['Android&iOS', 'Android', 'iOS'])
	parser.add_argument("mode", choices=['release', 'debug'])
	parser.add_argument("gamehallbranch")
	parser.add_argument("lobbybranch")
	parser.add_argument("env", choices=['r', 'pre', 'test'])
	parser.add_argument("-c", "--forceclean", action="store_true")
	parser.add_argument("-e", "--email", default="")
	parser.add_argument("-s", "--subhead", default="")
	parser.add_argument("-f", "--firapitoken", default="")
	parser.add_argument("-p", "--pngquant", action="store_true")
	parser.add_argument("-tid", "--taskid", default="")

	args = None
	try:
		args = parser.parse_args()

		# 对用户输入的中文进行转码
		# 判断环境的编码
		encoding = sys.getfilesystemencoding()
		print("sys.getfilesystemencoding() = %s" % encoding)

		if encoding != "utf-8":
			print("args.subhead = %s" % args.subhead)
			args.subhead = args.subhead.decode('gbk').encode('utf-8') #中文需要转码
			args.email = args.email.decode('gbk').encode('utf-8') #中文需要转码
			print("args.subhead = %s" % args.subhead)

		# --forceclean （注意：该参数只有当环境参数为 test 才生效，其他情况都强制设置为 True，避免正式环境打包出错），可选参数，是否强制重新编译 c++ 重新生成 .so
		if args.env != "test":
			args.forceclean = True

	finally:
		print("args = %s" % args)
		if args:
			return True, args
		else:
			return False, args

# 全局变量
tcsglobal = {}
tcsglobal["timestr"] = None
tcsglobal["daystr"] = None
tcsglobal["gameHallDir"] = None
tcsglobal["lobbyDir"] = None


def main():
	global tcsglobal

	tcsglobal["timestr"] = time.strftime("%Y%m%d-%H%M%S", time.localtime())
	tcsglobal["daystr"] = time.strftime("%Y%m%d", time.localtime())
	print("timestr = %s" % (tcsglobal["timestr"]))
	print("daystr = %s" % (tcsglobal["daystr"]))

	shell = "python"
	for v in sys.argv:
		shell = shell + " " + v
	print("shell: %s" % shell)

	# 读取参数
	result, args = parserArg()
	print("result %s : args = %s" % (result, str(args)))

	if not result:
		print("---------- build fail ----------")
		print("build shell = %s" % str(shell))

		if args.taskid:
			taskUtils.updateTaskStatus(args.taskid, taskUtils.TASK_STATUS_FAILED_ERROR_ARGUMENTS)

		if args.email:
			subject = "自动打包结果通知 %s %s" % (tcsglobal["timestr"], args.subhead)
			msg = """<p>---------- build fail ----------</p><p>build args is error!</p><p>build shell = %s </p>""" % (shell)
			print("email msg = %s" % msg)
			sendEmail(args.email, subject, msg)

		return

	# 测试环境的包单独使用另外一个目录，避免打包 Andorid 时重复编译 c++，提高打包速度
	envdirname = "r"
	if args.env == "test":
		envdirname = os.path.join("test", args.mode)

	tcsglobal["taskid"] = args.taskid
	tcsglobal["gameHallDir"] = os.path.join(config.PROJECT_ROOT, envdirname, config.GAME_HALL_DIR)
	tcsglobal["lobbyDir"] = os.path.join(config.PROJECT_ROOT, envdirname, config.LOBBY_DIR)
	print("taskid = %s" % (tcsglobal["taskid"]))
	print("gameHallDir = %s" % (tcsglobal["gameHallDir"]))
	print("lobbyDir = %s" % (tcsglobal["lobbyDir"]))

	# 下载源码
	# gitUtils.startGitTask(config.GAME_HALL_GIT_URL, tcsglobal["gameHallDir"], args.gamehallbranch, args.forceclean)
	# gitUtils.startGitTask(config.LOBBY_GIT_URL, tcsglobal["lobbyDir"], args.lobbybranch, args.forceclean)
	
	# 替换文件中的特定字符串
	changeFiles(args)

	if args.pngquant:
		# 在打包前，做一次图片压缩
		print("开始压缩图片...")
		curDir = os.getcwd()
		print("curDir = %s" % curDir)
		pngquantPath = None
		if sys.platform == "win32":
			pngquantPath = os.path.join(curDir, "libs/win/pngquant.exe")
		else:
			pngquantPath = os.path.join(curDir, "libs/mac/pngquant")

		print("pngquantPath = %s" % pngquantPath)
		pngUtils.config(pngquantPath)
		# pngUtils.quant_dir(os.path.join(tcsglobal["lobbyDir"], "src"))
		print("压缩图片完成")


	outfiles = []
	resultList = []

	if args.platform == "Android":
		result = build(args, "Android", outfiles)
		resultList.append(result)
	elif args.platform == "iOS":
		result = build(args, "iOS", outfiles)
		resultList.append(result)
	elif args.platform == "Android&iOS":
		print("build Android&iOS")
		result = build(args, "Android", outfiles)
		resultList.append(result)

		result = build(args, "iOS", outfiles)
		resultList.append(result)
	
	print("---------- build finish ----------")
	print("build shell = %s" % str(shell))
	print("outfiles = %s" % str(outfiles))
	print("ftp resultList = %s" % str(resultList))

	print("fir resultList = %s" % str(resultList))

	if args.email and len(resultList) > 0:
		try:
			sendSuccessEmail(args, shell, resultList)
		except:
			# 更新任务状态 - 打包成功，但发邮件失败
			taskUtils.updateTaskStatus(args.taskid, taskUtils.TASK_STATUS_SUCCESSED_EXCEPT_MAIL)

##################### test ###################

# 测试邮件
def testSendImagesEmail():
	mail_msg = """
	<p>Python 邮件发送测试...</p>
	<p><a href="http://www.runoob.com">菜鸟教程链接</a></p>
	<p>图片演示：</p>
	<p><img src="cid:img1"></p>
	<p><img src="cid:img2"></p>
	"""
	images = {"img1": "test-img.png", "img2": "test-img.png"}
	sendImagesEmail("eddy.wang@xiaoxiongyouxi.com", "dsafsa", mail_msg, images)

	# sendEmail("eddy.wang@xiaoxiongyouxi.com", "dsafsa", mail_msg)

class DottableDict(dict):
	def __init__(self, *args, **kwargs):
		dict.__init__(self, *args, **kwargs)
		self.__dict__ = self

	def allowDotting(self, state=True):
		if state:
			self.__dict__ = self
		else:
			self.__dict__ = dict()

def testSendSuccessEmail():
	args = {
		"platform": "Android",
		"mode": "debug",
		"env": "test",
		"email": "eddy.wang@xiaoxiongyouxi.com",
		"subhead": "testSendSuccessEmail",
		"firapitoken": "232dd0b3c85208a1900b72d6487fb142",
	}

	args = DottableDict(args)
	print(args.email)

	resultList = [
		{
			"success": True, "platform": "Android",
			"ftpurl": "ftpurl",
			"file": "tcs-test.apk", "filename": "tcs-test.apk",
			"installurl": "https://fir.im/9a23?release_id=5b487e4f548b7a39ddb72bcb"
		},
		{
			"success": True, "platform": "iOS",
			"ftpurl": "ftpurl",
			"file": "tcs-test.apk", "filename": "tcs-test.apk",
			"installurl": "https://fir.im/9a23?release_id=5b487e4f548b7a39ddb72bcb"
		}
	]
	sendSuccessEmail(args, "shell str", resultList)

def testToQRCodeImage():
	resultList = [
		{
			"success": True, "platform": "Android",
			"ftpurl": "ftpurl",
			"file": "tcs-test.apk", "filename": "tcs-test.apk",
			"installurl": "https://fir.im/9a23?release_id=5b487e4f548b7a39ddb72bcb"
		},
		{
			"success": True, "platform": "iOS",
			"ftpurl": "ftpurl",
			"file": "tcs-test.apk", "filename": "tcs-test.apk",
			"installurl": "https://fir.im/9a23?release_id=5b487e4f548b7a39ddb72bcb"
		}
	]

	toQRCodeImage("https://fir.im/9a23?release_id=测试图片压缩功能 85-95", "测试图片压缩功能 85-95", resultList, "qrcode.png")

def testUploadFileToFir():
	result = {
		"success": True, "platform": "Android",
		"ftpurl": "ftpurl",
		"file": "tcs-test.apk", "filename": "tcs-test.apk",
	}
	print("result = %s" % str(result))

	uploadFileToFir(result, "232dd0b3c85208a1900b72d6487fb142", "测试上传 fir 功能")

	print("fir result = %s" % str(result))

if __name__ == "__main__":
	main()

	# testSendImagesEmail()

	# urlToQRCode('https://fir.im/9a23?release_id=5b487e4f548b7a39ddb72bcb', 'test_qrcode.png')

	# testSendSuccessEmail()

	# testToQRCodeImage()

	# testUploadFileToFir()


